import random
import matplotlib.pyplot as plt
from openpyxl import Workbook


def generate_students():
    students = {}
    for i in range(15):
        name = chr(ord('A') + i)
        score = random.randint(35, 100)
        students[name] = score
    return students


def plot_histogram(scores):
    plt.hist(scores, bins=10, edgecolor='black')
    plt.title("学生成绩分布直方图")
    plt.xlabel("分数")
    plt.ylabel("人数")
    plt.show()


def save_to_excel(students):
    wb = Workbook()
    ws = wb.active
    ws.append(["姓名", "成绩"])
    for name, score in students.items():
        ws.append([name, score])
    wb.save("学生成绩表.xlsx")
    print("Excel文件生成成功！")


def calculate_statistics(scores):
    average = sum(scores) / len(scores)
    maximum = max(scores)
    minimum = min(scores)
    fail_count = sum(1 for score in scores if score < 60)
    return average, maximum, minimum, fail_count


def main():
    students = generate_students()
    print("学生字典:", students)

    scores = list(students.values())
    plot_histogram(scores)

    save_to_excel(students)

    sorted_students = dict(sorted(students.items(), key=lambda item: item[1], reverse=True))
    print("按照学生成绩降序排列的字典:", sorted_students)

    average, maximum, minimum, fail_count = calculate_statistics(scores)
    print("平均分: {:^7.2f}".format(average))
    print("最大值: {:^7.2f}".format(maximum))
    print("最小值: {:^7.2f}".format(minimum))
    print("不及格人数:", fail_count)

    query_count = 0

    while True:
        name = input("请输入学生名字（A到O之间的大写字母）：")
        if name in students:
            score = students[name]
            if score > average:
                print("该生成绩属于上等水平")
            elif score == average:
                print("该生成绩属于中等水平")
            else:
                print("该生成绩属于下等水平")
        else:
            print("请输入正确的学生名字")

        choice = input("是否继续循环？（输入 'y' 继续，输入 'n' 停止）：")
        query_count += 1

        if choice.lower() == 'n':
            break

    print("查询次数:", query_count)


if __name__ == "__main__":
    main()
